import { Injectable, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import { Express } from 'express';

@Injectable()
export class UploadService {
  private readonly uploadDir: string;

  constructor(private configService: ConfigService) {
    // 从环境变量获取上传目录，默认为 public/uploads
    this.uploadDir = this.configService.get('UPLOAD_DIR', 'public/uploads');
    
    // 确保 public 目录存在
    const publicDir = path.join(process.cwd(), 'public');
    if (!fs.existsSync(publicDir)) {
      fs.mkdirSync(publicDir, { recursive: true });
    }
    
    // 确保上传目录存在
    if (!fs.existsSync(this.uploadDir)) {
      fs.mkdirSync(this.uploadDir, { recursive: true });
    }
  }

  async uploadFile(file: Express.Multer.File): Promise<{ url: string; filename: string; mimetype: string; size: number }> {
    try {
      // 生成唯一文件名
      const uniqueSuffix = crypto.randomBytes(8).toString('hex');
      const originalName = file.originalname;
      const ext = path.extname(originalName);
      const filename = `${uniqueSuffix}${ext}`;
      
      // 构建文件保存路径
      const filePath = path.join(this.uploadDir, filename);
      
      // 保存文件
      await fs.promises.writeFile(filePath, file.buffer);

      // 构建文件访问URL
      const baseUrl = this.configService.get('BASE_URL', 'http://localhost:3000');
      const url = `${baseUrl}/uploads/${filename}`;

      return {
        url,
        filename,
        mimetype: file.mimetype,
        size: file.size,
      };
    } catch (error) {
      throw new BadRequestException('文件上传失败');
    }
  }
} 